<style>
    .layui-form-label {
        width: 100px;
    }
    .layui-input-block {
        margin-left: 130px;
    }
    .companyFormPhotos {
        margin-left: 50px;
        line-height: 38px;
        float: left;
        margin-right: 30px;
    }

    .companyFormPhotos img {
        height: 38px;
        width: auto;
        max-width: 200px;
    }

    .attachments{
        cursor: pointer;
        display: block;
        float: left;
        overflow:hidden;
        text-align: center;
        padding: 0 10px;
        width: 100px;
    }
    .option-item{
        overflow: hidden;
        color: #1E9FFF;
        text-align: center;
        height: 20px;
        line-height: 20px;
    }
    .preview{
        cursor: pointer;
        float: left;
    }
    .download{
        cursor: pointer;
        float: right;
    }
    .file-a{
        font-size: 12px;
        word-break: break-all;
        text-overflow: ellipsis;
        overflow: hidden;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        margin-top: 5px;
    }
    .info_row{
        height: 30px;
        line-height: 30px;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline" id="categorySearch">
                                    <label class="layui-form-label w-auto">合同分类：</label>
                                    <input name="contractCategoryId" type="hidden" />
                                    <div class="layui-input-inline mr0" id="selContractCategory">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">签约主体名称：</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="companyName" class="layui-input" type="text" placeholder="请输入签约主体名称"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">合同编号：</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="code" class="layui-input" type="text" placeholder="请输入编号"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">供应商签约人：</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="contactName" class="layui-input" type="text" placeholder="请输入签约主体名称"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">时间段：</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="createTime" id="pTime" class="layui-input date-icon" type="text"
                                               placeholder="选择时间" style="width: 200px" readonly/>
                                    </div>
                                    <input name="startCreateTime" id="sTime" type="hidden"/>
                                    <input name="endCreateTime" id="eTime" type="hidden"/>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" layui-form-keyDownSearch="true" lay-submit>查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="contractBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
                        </div>
                        <div class="lay-btn-rt">

                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="contractTable" lay-filter="contractTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="contractTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="view">详情</a>
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="changeRecord">变更记录</a>
    {{# if(d.status == 'hasSign'){ }}
    <a class="layui-btn layui-btn-xs" lay-event="relatedProduct">物料</a>
    {{# } }}
</script>

<script type="text/html" id="viewAttachmentBar">
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="viewAttachment">查看附件</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="contractForm">
    <form lay-filter="contractForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-col-xs6">
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>合同主体类型</label>
            <div class="layui-input-block">
                <select name="type" disabled></select>
            </div>
        </div>
        </div>
        <div class="layui-col-xs6">
        <div class="layui-form-item" id="PID">
            <label class="layui-form-label"><span style="color: red">*</span>合同分类</label>
            <input name="contractCategoryId" type="hidden" lay-verify="contractCategoryId" />
            <div class="layui-input-block" id="selectContractCategory">
            </div>
        </div>
        </div>
        <div class="layui-col-xs6">
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>签约主体名称</label>
            <div class="layui-input-block">
                <select name="subjectId" lay-filter="getSubject" lay-verify="required" required lay-search></select>
            </div>
        </div>
        </div>
        <div class="layui-col-xs6">
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>合同名称</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入合同名称" type="text" class="layui-input" maxlength="200" lay-verify="required" required/>
            </div>
        </div>
        </div>
        <div class="layui-col-xs6">
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>合同编号</label>
            <div class="layui-input-block">
                <input name="code" placeholder="请输入合同编号" type="text" class="layui-input" maxlength="200" lay-verify="required" required/>
            </div>
        </div>
        </div>
        <div class="layui-col-xs6">
        <div class="layui-form-item">
            <label class="layui-form-label">客户签约人</label>
            <div class="layui-input-block">
                <select name="contactsId" lay-search></select>
            </div>
        </div>
        </div>
        <div class="layui-col-xs6">
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>我方签约人</label>
            <div class="layui-input-block">
                <select name="contractor" lay-verify="required" required lay-search></select>
            </div>
        </div>
        </div>
        <div class="layui-col-xs6">
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>信息审批人</label>
            <div class="layui-input-block">
                <select name="approver" lay-verify="required" required lay-search></select>
            </div>
        </div>
        </div>
        <div class="layui-col-xs6">
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>签约金额</label>
            <div class="layui-input-block">
                <input name="amount" placeholder="请输入签约金额" type="text" class="layui-input" lay-verify="required|decimal" required/>
            </div>
        </div>
        </div>
        <div class="layui-col-xs12">
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>上传附件11</label>
            <div class="layui-input-block">
                <div class=" layui-btn" id="addDevicePicBtn" style="float: left;margin-left: 3px"><i class="layui-icon">&#xe681;</i>上传PDF文件
                </div>
                <div id="addHeaderImg" class="companyFormPhotos"></div>
                <input name="attachment" id="attachment" type="hidden" class="layui-input" lay-verify="attachment" />
            </div>
        </div>
        </div>
        <div class="layui-col-xs12">
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea name="remark" placeholder="请输入备注" maxlength="200" class="layui-textarea"></textarea>
            </div>
        </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="contractFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- 详情 -->
<script type="text/html" id="contractView">
    <div style="padding: 20px;">
        <table class="layui-table">
            <thead>
            <tr>
                <th style="width: 35%;">合同信息</th>
                <th>合同PDF预览内容</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td id="contractInfo">
                </td>
                <td>
                    <div id="attachmentName" style="margin-bottom: 10px; font-size: 16px;">合同附件：</div>
                    <div id="example1" style="height: 500px;"></div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</script>

<!-- 审核 -->
<script type="text/html" id="contractAuditForm">
    <form lay-filter="contractAuditForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label">审核意见</label>
            <div class="layui-input-block">
                <textarea name="auditOpinion" placeholder="请输入审核意见" maxlength="200" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn" data-status="success" lay-filter="contractAuditFormSubmit" lay-submit>审核通过</button>
            <button class="layui-btn layui-btn-danger" data-status="fail" lay-filter="contractAuditFormSubmit" lay-submit>审核不通过</button>
        </div>
    </form>
    <div style="padding: 20px;">
        <table class="layui-table">
            <thead>
            <tr>
                <th style="width: 35%;">合同信息</th>
                <th>合同PDF预览内容</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td id="contractInfo">
                </td>
                <td>
                    <div id="attachmentName" style="margin-bottom: 10px; font-size: 16px;">合同附件：</div>
                    <div id="example1" style="height: 500px;"></div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</script>

<!-- 合同信息 -->
<script type="text/html" id="contractInfoHtml">
    <div class="info_row">客户名称：{{d.companyName}}</div>
    <div class="info_row">合同名称：{{d.name}}</div>
    <div class="info_row">合同编号：{{d.code}}</div>
    <div class="info_row">客户签约人：{{d.contactName}}</div>
    <div class="info_row" id="contractorName">我方签约人：{{d.contractorName}}</div>
    <div class="info_row">签约时间：{{d.signingTime ? d.signingTime : ""}}</div>
    <div class="info_row">交货时间：{{d.deliveryTime ? d.deliveryTime : ""}}</div>
    <div class="info_row">备注信息：{{d.remark}}</div>
    <div class="info_row">合同金额：{{d.amount}}</div>
    <div style="overflow: hidden; padding: 5px 0;">
        <div style="float: left;">合同附件：</div>
        {{# var attachment = "";
        if(d.attachment){
        attachment = d.attachment.substring(d.attachment.lastIndexOf("/")+1);
        }
        var time = timeStamp2String(d.createTime);
        }}
        <div class="attachments">
            <div onclick="previewFile('{{attachment}}', '{{d.attachment}}');">
                <img src="../../../admin/assets/images/attachmentsIcon/pdf.png">
                <span class="file-a">{{attachment}}</span>
                <span class="file-a">{{time}}</span>
            </div>
        </div>
    </div>
    <div class="info_row">合同存放地点：{{d.address ? d.address : ""}}</div>
    <div class="info_row" id="keeperName">合同保管员：{{d.keeperName ? d.keeperName : ""}}</div>
    <!--<div class="info_row">合同状态：{{d.statusDesc}}</div>-->
    <div class="info_row" id="approverName">信息审批人：{{d.approverName ? d.approverName : ""}}</div>
    <div class="info_row">审核结果：{{d.statusDesc ? d.statusDesc : ""}}</div>
    <div class="info_row">审核意见备注：{{d.auditOpinion ? d.auditOpinion : ""}}</div>
</script>

<!-- 查看附件 -->
<script type="text/html" id="viewAttachmentHtml">
    <div id="example1" style="height: 100%;"></div>
</script>


<!-- 变更记录 -->
<script type="text/html" id="contractChangeRecord">
    <div class="layui-card">
        <div class="layui-card-body" id="changeRecord">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">合同编号：</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="code" class="layui-input" type="text" placeholder="请输入编号"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="contractChangeRecordFormSubSearchLog" lay-submit>查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="contractChangeRecordResets" lay-submit>重置</button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows" id="opBtn">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="contractChangeRecordBtnAdd" class="layui-btn icon-btn color-reseda">添加合同变更记录</button>
                        </div>
                        <div class="lay-btn-rt"></div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="contractChangeRecordTable" lay-filter="contractChangeRecordTable"></table>
        </div>
    </div>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="contractChangeRecordForm">
    <form lay-filter="contractChangeRecordForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item" id="PID">
            <label class="layui-form-label"><span style="color: red">*</span>合同分类</label>
            <input name="contractCategoryId" type="hidden" lay-verify="contractCategoryId" />
            <div class="layui-input-block" id="selectContractCategory">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>签约主体名称</label>
            <div class="layui-input-block">
                <input name="companyName" type="text" class="layui-input" style="border: 0;" readonly />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>合同名称</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入合同名称" type="text" class="layui-input" maxlength="200" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>合同编号</label>
            <div class="layui-input-block">
                <input name="code" placeholder="请输入合同编号" type="text" class="layui-input" readonly maxlength="200" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>客户签约人</label>
            <div class="layui-input-block">
                <select name="contactsId" lay-verify="required" required lay-search></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>我方签约人</label>
            <div class="layui-input-block">
                <select name="contractor" lay-verify="required" required lay-search></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>签约时间</label>
            <div class="layui-input-block">
                <input name="signingTime" id="signingTime" placeholder="请选择签约时间" type="text" class="layui-input" readonly lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>信息审批人</label>
            <div class="layui-input-block">
                <select name="approver" lay-verify="required" required lay-search></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注信息</label>
            <div class="layui-input-block">
                <textarea name="remark" placeholder="请输入备注信息" maxlength="200" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>上传附件</label>
            <div class="layui-input-block">
                <div class=" layui-btn"id='addDevicePicBtnEdit' style="float: left;margin-left: 3px"><i class="layui-icon">&#xe681;</i>上传PDF文件
                </div>
                <div id="addHeaderImg" class="companyFormPhotos"></div>
                <input name="attachment" id="attachment" type="hidden" class="layui-input" lay-verify="attachment" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>签约金额</label>
            <div class="layui-input-block">
                <input name="amount" placeholder="请输入签约金额" type="text" class="layui-input" lay-verify="required|decimal" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>是否最终版</label>
            <div class="layui-input-block">
                <input name="isFinal" type="checkbox" lay-skin="switch" lay-filter="isFinal" lay-text="是|否"/>
            </div>
        </div>
        <div id="content" style="display: none;">
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color: red">*</span>交货时间</label>
                <div class="layui-input-block">
                    <input name="deliveryTime" id="deliveryTime" placeholder="请选择交货时间" type="text" class="layui-input" readonly />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color: red">*</span>合同存放地点</label>
                <div class="layui-input-block">
                    <input name="address" placeholder="请输入合同存放地点" type="text" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color: red">*</span>合同保管员</label>
                <div class="layui-input-block">
                    <select name="keeper" ></select>
                </div>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="contractChangeRecordFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- 表格操作列 -->
<script type="text/html" id="contractChangeRecordTableBar">
    {{# if(d.status == 'stayAudit' || d.status == 'fail'){ }}
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    {{# } }}
    <a class="layui-btn layui-btn-xs" lay-event="view">详情</a>
    {{# if(d.status == 'stayAudit'){ }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="audit">审核</a>
    {{# } }}
    {{# if(d.status == 'success'){ }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="final">终版</a>
    {{# } }}
</script>

<!-- 终版弹窗 -->
<script type="text/html" id="contractFinalForm">
    <form lay-filter="contractFinalForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>交货时间</label>
            <div class="layui-input-block">
                <input name="deliveryTime" id="deliveryTime" placeholder="请选择交货时间" type="text" class="layui-input" readonly lay-verify="required" required  />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>合同存放地点</label>
            <div class="layui-input-block">
                <input name="address" placeholder="请输入合同存放地点" type="text" class="layui-input" lay-verify="required" required  />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>合同保管员</label>
            <div class="layui-input-block">
                <select name="keeper" lay-verify="required" required lay-search></select>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="contractFinalFormSubmit" lay-submit>确认终版</button>
        </div>
    </form>
</script>

<!-- 关联物料 -->
<script type="text/html" id="contractRelatedProduct">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 表格 -->
            <table class="layui-table" id="contractRelatedProductContractTable" lay-filter="contractRelatedProductContractTable"></table>

            <!-- 表格 -->
            <table class="layui-table" id="contractRelatedProductTable" lay-filter="contractRelatedProductTable"></table>
        </div>
    </div>
</script>

<!-- 联系客户 -->
<script type="text/html" id="customerPhoneBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="viewCustomerPhone">联系客户</a>
</script>


<!-- js部分 -->
<script type="text/javascript" src="../../../admin/assets/js/pdfobject.min.js"></script>
<script type="text/javascript" src="../../../admin/assets/js/jsencrypt.min.js"></script>
<script>
    var $,config;

    // 预览文件
    function previewFile(realName, url) {
        $("#attachmentName").text("合同附件："+realName);
        PDFObject.embed(url, "#example1");
    }

    //下载文件
    function downloadFile(realName, url) {
        var $downForm = $("<form method='get'></form>");
        $downForm.attr("action", config.upload_url + 'downloadFile');
        var $input = $("<input type='hidden'>");
        $input.attr("name","url");
        $input.val(url);
        $downForm.append($input);
        var $input1 = $("<input type='hidden'>");
        $input1.attr("name","filename");
        $input1.val(realName);
        $downForm.append($input1);
        var $input2 = $("<input type='hidden'>");
        $input2.attr("name","access_token");
        var publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcLt6aJfWmRid+8Cuirv9Zi8sVfhSJ+pUkL7dC+M1yc+e6zr+PQj8sbl2jV5ZBhF4VwoIHWzFLoxNKSizukUNzumJi1KwhjmbASN2EVBKUhJwmx422oew9WCnZYE9+/T+xF87Diie3uQm+7cYVCpvlpqnf9zMBB0Js9zYjOPtP4wIDAQAB";
        var crypt = new JSEncrypt();
        crypt.setKey(publicKey);
        var token = "Bearer "+config.getToken();
        var tokenLeft = token.substring(0,50);
        var tokenRight = token.substring(50);
        var enc = crypt.encrypt(tokenLeft);
        $input2.val(enc+tokenRight);
        $downForm.append($input2);
        $(document.body).append($downForm);
        //提交表单，实现下载
        $downForm.submit();
    }

    //在Jquery里格式化Date日期时间数据
    function timeStamp2String(time){
        var datetime = new Date(time);
        var year = datetime.getFullYear();
        var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
        var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
        var hour = datetime.getHours()< 10 ? "0" + datetime.getHours() : datetime.getHours();
        var minute = datetime.getMinutes()< 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
        var second = datetime.getSeconds()< 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
        // return year + "-" + month + "-" + date+" "+hour+":"+minute+":"+second;
        return year + "年" + month + "月" + date + "日";
    }

    layui.use(['layer', 'form', 'table', 'admin', 'upload', 'laytpl', 'laydate'], function () {
        $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var laytpl = layui.laytpl;
        var laydate = layui.laydate;

        // 获取合同分类
        admin.req('enterprise/contract/admin/contractCategory/getTreeData', {type: "client"}, function(res) {
            if (200 == res.code) {
                xmSelect.render({
                    el: '#selContractCategory',
                    model: {label: {type: 'text'}},
                    radio: true,
                    clickClose: true,
                    filterable: true,
                    tree: {
                        show: true,
                        strict: false,
                        /*expandedKeys: [-1],*/
                        expandedKeys: true,
                    },
                    tips: '顶级分类',
                    height: 'auto',
                    data() {
                        return res.data;
                    },
                    on: function (data) {
                        //被选中的select的id,如果没有 -1
                        let contractCategoryId = data.arr.length > 0 ? data.change[0].value : "";
                        $("input[name='contractCategoryId']").val(contractCategoryId);
                    },
                });
            } else {
                layer.msg('获取合同分类失败!', {icon : 2, time : 1000});
            }
        }, 'GET');

        //时间范围
        laydate.render({
            elem: '#pTime',
            type: 'date',
            range: true,
            done: function (value, date, endDate) {
                if (value){
                    var dateValue = value.split(" - ");
                    $("#sTime").val(dateValue[0]+ " 00:00:00");
                    $("#eTime").val(dateValue[1]+" 23:59:59");
                }else {
                    $("#sTime").val('');
                    $("#eTime").val('');
                }
            }
        });

        // 渲染表格
        var insTb = table.render({
            elem: '#contractTable',
            url: config.base + 'enterprise/sell/admin/customerContract/list',
            toolbar: true,
            defaultToolbar: ["filter"],
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers'}
                ,{field: 'code', align:'center', title: '合同编号', width: 150}
                ,{field: 'typeDesc', align:'center', title: '合同主体类型', width: 140}
                ,{field: '', align:'center', title: '关联订单数', width: 120}
                ,{field: 'companyName', align:'center', title: '客户名称', width: 120}
                ,{field: 'contractCategoryName', align:'center', title: '合同分类', width: 120}
                ,{field: 'createTime', align:'center', title: '创建时间', width: 160}
                ,{field: 'contactName', align:'center', title: '客户签约人', width: 120}
                ,{field: 'amount', align:'center', title: '签约金额', width: 110}
                ,{field: 'attachment', align:'center', title: '合同附件', width: 110, toolbar: '#viewAttachmentBar'}
                ,{field: 'statusDesc', align:'center', title: '合同状态', width: 110}
                ,{align: 'center', toolbar: '#contractTableBar', title: '操作', width: 220}
            ]],
            done: function (res, curr, count) {
                //移除按钮
                var menuButton = config.getMenuButton(location.hash);
              // if(menuButton.indexOf("搜索") == -1){
              //     $('.layui-form.toolbar').remove();
              // }
              // if(menuButton.indexOf("修改") == -1){
              //     $("[lay-event='edit']").remove();
              // }
              // if(menuButton.indexOf("删除") == -1){
              //     $("[lay-event='del']").remove();
              // }
            }
        });

        // 工具条点击事件
        table.on('tool(contractTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            } else if (obj.event === 'view') { // 详情
                showViewModel(data);
            } else if (obj.event === 'changeRecord') { // 变更记录
                showChangeRecordModel(data);
            } else if (obj.event === 'relatedProduct') { // 物料
                showRelatedProductModel(data);
            } else if (obj.event === 'viewAttachment') { // 查看附件
                showViewAttachmentModel(data);
            }
        });

        //监听排序
        table.on('sort(contractTable)', function(obj){
            table.reload('contractTable', {
                initSort: obj
                ,where: {
                    sort: obj.field
                    ,order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field,page: {curr: 1}},'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            $(".lay-header").find('select').val("");
            $(".lay-header").find('input').val("");
            let field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
        });

        // 添加按钮点击事件
        $('#contractBtnAdd').click(function () {
            showEditModel();
        });

        // 显示编辑弹窗
        function showEditModel(data) {
            admin.open({
                type: 1,
                area: '800px',
                offset: '150px',
                title: data ? '修改合同' : '添加合同',
                content: $('#contractForm').html(),
                success: function () {
                    //自定义验证规则
                    form.verify({
                        decimal: [/^[0-9]*(\.[0-9]{1,2})?$/, '格式错误'],
                        contractCategoryId: function (value) {
                            if(value == ""){
                                return "请选择合同分类";
                            }
                        },
                        attachment: function (value) {
                            if(value == ""){
                                return "请上传附件";
                            }
                        }
                    })

                    // 获取合同主体类型
                    admin.req('enterprise/contract/admin/contractCategory/types', {}, function(res) {
                        if (200 == res.code) {
                            $.each(res.data, function(index, item) {
                                $("form select[name='type']").append(new Option(item.name, item.id));//往下拉菜单里添加元素
                            })
                            $("form select[name='type']").find("option").each(function (index, item) {
                                // 默认主体类型为供应商
                                if($(item).val() == "client"){
                                    $(item).attr("selected", true);
                                }
                            })
                            form.render(); //菜单渲染 把内容加载进去
                        } else {
                            layer.msg('获取合同主体类型失败!', {icon : 2, time : 1000});
                        }
                    }, 'GET');

                    var selectId = null;
                    if(data && data.contractCategoryId){
                        selectId = data.contractCategoryId;
                    }
                    // 获取合同分类
                    admin.req('enterprise/contract/admin/contractCategory/getTreeData', {selectId: selectId, type: "client"}, function(res) {
                        if (200 == res.code) {
                            xmSelect.render({
                                el: '#selectContractCategory',
                                model: {label: {type: 'text'}},
                                radio: true,
                                clickClose: true,
                                filterable: true,
                                tree: {
                                    show: true,
                                    strict: false,
                                    /*expandedKeys: [-1],*/
                                    expandedKeys: true,
                                },
                                tips: '顶级分类',
                                height: 'auto',
                                data() {
                                    return res.data;
                                },
                                on: function (data) {
                                    //被选中的select的id,如果没有 -1
                                    let contractCategoryId = data.arr.length > 0 ? data.change[0].value : "";
                                    $("input[name='contractCategoryId']").val(contractCategoryId);
                                },
                            });
                        } else {
                            layer.msg('获取合同分类失败!', {icon : 2, time : 1000});
                        }
                    }, 'GET');

                    // 获取签约主体
                    admin.req('enterprise/sell/admin/customersInfo/getBasicInfo', {customerType:"2,3"}, function(res) {
                        console.log(res.data);
                        if (200 == res.code) {

                            $("form select[name='subjectId']").append(new Option("请选择签约主体", ""));//往下拉菜单里添加元素
                            $.each(res.data, function(index, item) {
                                $("form select[name='subjectId']").append(new Option(item.customerName, item.id));//往下拉菜单里添加元素
                            })
                            form.render(); //菜单渲染 把内容加载进去
                            if(data && data.subjectId){
                                form.val('contractForm', data);
                            }
                            form.on("select(getSubject)", function (data) {
                                if(data.value){
                                    // 获取客户签约人
                                    admin.req('enterprise/sell/admin/contactInfo/list', {limit: 99999, selCustomerId: data.value}, function(res) {
                                        if (200 == res.code) {
                                            $("form select[name='contactsId']").html("");
                                            $("form select[name='contactsId']").append(new Option("请选择客户签约人", ""));//往下拉菜单里添加元素
                                            $.each(res.data, function(index, item) {
                                                $("form select[name='contactsId']").append(new Option(item.name+"("+item.telephone+")", item.id));//往下拉菜单里添加元素
                                            })
                                            form.render(); //菜单渲染 把内容加载进去
                                            if(data && data.contactsId){
                                                form.val('contractForm', data);
                                            }
                                        } else {
                                            layer.msg('获取客户签约人失败!', {icon : 2, time : 1000});
                                        }
                                    }, 'GET');
                                }else{
                                    $("form select[name='contactsId']").html("");
                                }
                            })
                        } else {
                            layer.msg('获取签约主体失败!', {icon : 2, time : 1000});
                        }
                    }, 'GET');

                    // 获取我方签约人
                    admin.req('user/admin/user/list', {limit: 99999}, function(res) {
                        console.log(res.data);
                        if (200 == res.code) {
                            $("form select[name='contractor']").append(new Option("请选择我方签约人", ""));//往下拉菜单里添加元素
                            $.each(res.data, function(index, item) {
                                $("form select[name='contractor']").append(new Option(item.nickname+"("+item.username+")", item.id));//往下拉菜单里添加元素
                            })
                            form.render(); //菜单渲染 把内容加载进去
                            if(data && data.contractor){
                                form.val('contractForm', data);
                            }
                        } else {
                            layer.msg('获取我方签约人失败!', {icon : 2, time : 1000});
                        }
                    }, 'GET');

                    // 获取信息审批人
                    admin.req('user/admin/user/list', {limit: 99999}, function(res) {
                        console.log(res.data);
                        if (200 == res.code) {
                            $("form select[name='approver']").append(new Option("请选择信息审批人", ""));//往下拉菜单里添加元素
                            $.each(res.data, function(index, item) {
                                $("form select[name='approver']").append(new Option(item.nickname+"("+item.username+")", item.id));//往下拉菜单里添加元素
                            })
                            form.render(); //菜单渲染 把内容加载进去
                            if(data && data.approver){
                                form.val('contractForm', data);
                            }
                        } else {
                            layer.msg('获取信息审批人失败!', {icon : 2, time : 1000});
                        }
                    }, 'GET');

                 
                    form.val('contractForm', data);
                          // 上传附件
                          upload.render({
                            elem: '#addDevicePicBtn'
                            , url: config.upload_url + 'uploadFile'
                            , data: {}
                            , accept: 'file'
                            , exts: 'pdf'
                            , headers: {Authorization: 'Bearer ' + config.getToken()}
                            , done: function (res) {
                                if (res.code == 200) {
                                    layer.msg(res.msg || "上传成功", {icon: 1});
                                    let imagUrl = res.data.url;
                                    var name = res.data.fileName;
                                    $('#addHeaderImg').html('<div class="attachments">' +
                                        '<div><img src="../../../admin/assets/images/attachmentsIcon/pdf.png"><span class="file-a">'+name+'</span></div></div>');
                                    $('#attachment').val(imagUrl);

                                    $(".attachments").click(function () {
                                        var json = {};
                                        json.attachment = imagUrl;
                                        showViewAttachmentModel(json);
                                    })
                                } else if (res.code == 502) {
                                    return location.replace('admin/login.html');
                                } else {
                                    layer.msg(res.msg || "上传失败", {icon: 2});
                                }
                            }
                        });

                    // 表单提交事件
                    form.on('submit(contractFormSubmit)', function (d) {
                        layer.load(2);
                        admin.req(data ? 'enterprise/sell/admin/customerContract/update' : 'enterprise/sell/admin/customerContract/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('contractTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprise/sell/admin/customerContract/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        // 显示详情弹窗
        function showViewModel(data) {
            admin.open({
                type: 1,
                area: ['80%', '80%'],
                title: '合同详情',
                content: $('#contractView').html(),
                success: function () {
                    // 查询我方签约人
                    admin.req('user/admin/user/list', {limit: 99999}, function(res) {
                        console.log(res.data);
                        if (200 == res.code) {
                            $.each(res.data, function(index, item) {
                                if(item.id == data.contractor){
                                    $("#contractorName").text("我方签约人："+item.nickname+"("+item.username+")");
                                }
                            })
                        } else {
                            layer.msg('获取我方签约人失败!', {icon : 2, time : 1000});
                        }
                    }, 'GET');

                    // 查询合同保管员
                    admin.req('user/admin/user/list', {limit: 99999}, function(res) {
                        if (200 == res.code) {
                            $.each(res.data, function(index, item) {
                                if(item.id == data.keeper){
                                    $("#keeperName").text("合同保管员："+item.nickname+"("+item.username+")");
                                }
                            })
                        } else {
                            layer.msg('获取合同保管员失败!', {icon : 2, time : 1000});
                        }
                    }, 'GET');

                    // 查询信息审批人
                    admin.req('user/admin/user/list', {limit: 99999}, function(res) {
                        if (200 == res.code) {
                            $.each(res.data, function(index, item) {
                                if(item.id == data.approver){
                                    $("#approverName").text("信息审批人："+item.nickname+"("+item.username+")");
                                }
                            })
                        } else {
                            layer.msg('获取信息审批人失败!', {icon : 2, time : 1000});
                        }
                    }, 'GET');

                    $("#attachmentName").text("合同附件："+data.attachment.substring(data.attachment.lastIndexOf("/")+1));

                    laytpl(contractInfoHtml.innerHTML).render(data, function (html) {
                        $("#contractInfo").html(html);
                    });

                    if(data.attachment){
                        PDFObject.embed(data.attachment, "#example1");
                    }
                }
            })
        }

        // 变更记录
        function showChangeRecordModel(data) {
            var supplierContract = data;
            admin.open({
                type: 1,
                area: ['80%', '800px'],
                title: '合同变更记录',
                content: $('#contractChangeRecord').html(),
                success: function () {
                    isShowAddBtn(supplierContract);

                    // 渲染表格
                    var changeRecordInsTb = table.render({
                        elem: '#contractChangeRecordTable',
                        url: config.base + 'enterprise/sell/admin/customerContract/contractChangeRecordList',
                        where: {contractId: supplierContract.id},
                        page: true,
                        cellMinWidth: 100,
                        cols: [[
                            {type: 'numbers'}
                            ,{field: 'code', align:'center', title: '合同编号', width: 150}
                            ,{field: 'typeDesc', align:'center', title: '合同主体类型', width: 140}
                            ,{field: 'companyName', align:'center', title: '客户名称', width: 120}
                            ,{field: 'contractCategoryName', align:'center', title: '合同分类', width: 120}
                            ,{field: 'createTime', align:'center', title: '创建时间', width: 170}
                            ,{field: 'contactName', align:'center', title: '客户签约人', width: 120}
                            ,{field: 'amount', align:'center', title: '签约金额', width: 110}
                            ,{field: 'attachment', align:'center', title: '合同附件', width: 110, toolbar: '#viewAttachmentBar'}
                            ,{field: 'statusDesc', align:'center', title: '合同状态', width: 110}
                            ,{align: 'center', toolbar: '#contractChangeRecordTableBar', title: '操作', width: 100}
                        ]],
                        done: function (res, curr, count) {

                        }
                    });

                    // 工具条点击事件
                    table.on('tool(contractChangeRecordTable)', function (obj) {
                        var data = obj.data;
                        if (obj.event === 'edit') { // 修改
                            showEditModel(data);
                        } else if (obj.event === 'view') { // 详情
                            showViewModel(data);
                        } else if (obj.event === 'audit') { // 审核
                            showAuditModel(data);
                        } else if (obj.event === 'final') { // 终版
                            doFinal(data);
                        } else if (obj.event === 'viewAttachment') { // 查看附件
                            showViewAttachmentModel(data);
                        }
                    });

                    // 搜索
                    form.on('submit(contractChangeRecordFormSubSearchLog)', function (data) {
                        changeRecordInsTb.reload({where: data.field,page: {curr: 1}},'data');
                    });

                    // 重置搜索
                    form.on('submit(contractChangeRecordResets)', function (data) {
                        $("#changeRecord").find(".lay-header").find('select').val("");
                        $("#changeRecord").find(".lay-header").find('input').val("");
                        let field = data.field;
                        for (let key in field) {
                            field[key] = ''
                        }
                        changeRecordInsTb.reload({where: field, page: {curr: 1}}, 'data');
                    });

                    // 添加按钮点击事件
                    $('#contractChangeRecordBtnAdd').click(function () {
                        showEditModel();
                    });

                    // 显示编辑弹窗
                    function showEditModel(data) {
                        var contractChangeRecord = admin.open({
                            type: 1,
                            area: ['800px', '80%'],
                            offset: '65px',
                            title: data ? '修改合同变更记录' : '添加合同变更记录',
                            content: $('#contractChangeRecordForm').html(),
                            success: function () {
                                //自定义验证规则
                                form.verify({
                                    decimal: [/^[0-9]*(\.[0-9]{1,2})?$/, '格式错误'],
                                    contractCategoryId: function (value) {
                                        if(value == ""){
                                            return "请选择合同分类";
                                        }
                                    },
                                    attachment: function (value) {
                                        if(value == ""){
                                            return "请上传附件";
                                        }
                                    }
                                })

                                // 签约时间
                                laydate.render({
                                    elem: '#signingTime',
                                    type: 'date'
                                });

                                // 交货时间
                                laydate.render({
                                    elem: '#deliveryTime',
                                    type: 'date'
                                });

                                var selectId = null;
                                if(supplierContract && supplierContract.contractCategoryId){
                                    selectId = supplierContract.contractCategoryId;
                                }
                                if(data && data.contractCategoryId){
                                    selectId = data.contractCategoryId;
                                }
                                // 获取合同分类
                                admin.req('enterprise/contract/admin/contractCategory/getTreeData', {selectId: selectId, type: "client"}, function(res) {
                                    if (200 == res.code) {
                                        xmSelect.render({
                                            el: '#selectContractCategory',
                                            model: {label: {type: 'text'}},
                                            radio: true,
                                            clickClose: true,
                                            filterable: true,
                                            tree: {
                                                show: true,
                                                strict: false,
                                                /*expandedKeys: [-1],*/
                                                expandedKeys: true,
                                            },
                                            tips: '顶级分类',
                                            height: 'auto',
                                            data() {
                                                return res.data;
                                            },
                                            on: function (data) {
                                                //被选中的select的id,如果没有 -1
                                                let contractCategoryId = data.arr.length > 0 ? data.change[0].value : "";
                                                $("input[name='contractCategoryId']").val(contractCategoryId);
                                            },
                                        });
                                    } else {
                                        layer.msg('获取合同分类失败!', {icon : 2, time : 1000});
                                    }
                                }, 'GET');

                                var selCustomerId = null;
                                if(supplierContract && supplierContract.subjectId){
                                    selCustomerId = supplierContract.subjectId;
                                }
                                if(data && data.subjectId){
                                    selCustomerId = data.subjectId;
                                }
                                if(selCustomerId){
                                    // 获取客户签约人
                                    admin.req('enterprise/sell/admin/contactInfo/list', {limit: 99999, selCustomerId: selCustomerId}, function(res) {
                                        if (200 == res.code) {
                                            $("form select[name='contactsId']").html("");
                                            $("form select[name='contactsId']").append(new Option("请选择客户签约人", ""));//往下拉菜单里添加元素
                                            $.each(res.data, function(index, item) {
                                                $("form select[name='contactsId']").append(new Option(item.name+"("+item.telephone+")", item.id));//往下拉菜单里添加元素
                                            })
                                            form.render(); //菜单渲染 把内容加载进去
                                            if(data && data.contactsId){
                                                form.val('contractChangeRecordForm', data);
                                            }else{
                                                form.val('contractChangeRecordForm', supplierContract);
                                            }
                                        } else {
                                            layer.msg('获取客户签约人失败!', {icon : 2, time : 1000});
                                        }
                                    }, 'GET');
                                }


                                // 获取我方签约人
                                admin.req('user/admin/user/list', {limit: 99999}, function(res) {
                                    if (200 == res.code) {
                                        $("form select[name='contractor']").append(new Option("请选择我方签约人", ""));//往下拉菜单里添加元素
                                        $.each(res.data, function(index, item) {
                                            $("form select[name='contractor']").append(new Option(item.nickname+"("+item.username+")", item.id));//往下拉菜单里添加元素
                                        })
                                        form.render(); //菜单渲染 把内容加载进去
                                        if(data && data.contractor){
                                            form.val('contractChangeRecordForm', data);
                                        }else{
                                            form.val('contractChangeRecordForm', supplierContract);
                                        }
                                    } else {
                                        layer.msg('获取我方签约人失败!', {icon : 2, time : 1000});
                                    }
                                }, 'GET');

                                // 获取信息审批人
                                admin.req('user/admin/user/list', {limit: 99999}, function(res) {
                                    if (200 == res.code) {
                                        $("form select[name='approver']").append(new Option("请选择信息审批人", ""));//往下拉菜单里添加元素
                                        $.each(res.data, function(index, item) {
                                            $("form select[name='approver']").append(new Option(item.nickname+"("+item.username+")", item.id));//往下拉菜单里添加元素
                                        })
                                        form.render(); //菜单渲染 把内容加载进去
                                        if(data && data.approver){
                                            form.val('contractChangeRecordForm', data);
                                        }else{
                                            form.val('contractChangeRecordForm', supplierContract);
                                        }
                                    } else {
                                        layer.msg('获取信息审批人失败!', {icon : 2, time : 1000});
                                    }
                                }, 'GET');

                                // 上传附件
                                upload.render({
                                    elem: '#addDevicePicBtnEdit'
                                    , url: config.upload_url + 'uploadFile'
                                    , data: {}
                                    , accept: 'file'
                                    , exts: 'pdf'
                                    , headers: {Authorization: 'Bearer ' + config.getToken()}
                                    , done: function (res) {
                                        if (res.code == 200) {
                                            layer.msg(res.msg || "上传成功", {icon: 1});
                                            let imagUrl = res.data.url;
                                            var name = res.data.fileName;
                                            $('#addHeaderImg').html('<div class="attachments">' +
                                                '<div><img src="../../../admin/assets/images/attachmentsIcon/pdf.png"><span class="file-a">'+name+'</span></div></div>');
                                            $('#attachment').val(imagUrl);

                                            $(".attachments").click(function () {
                                                var json = {};
                                                json.attachment = imagUrl;
                                                showViewAttachmentModel(json);
                                            })
                                        } else if (res.code == 502) {
                                            return location.replace('admin/login.html');
                                        } else {
                                            layer.msg(res.msg || "上传失败", {icon: 2});
                                        }
                                    }
                                });

                                var attachment = "";
                                if(supplierContract && supplierContract.attachment){
                                    attachment = supplierContract.attachment;
                                }
                                if(data && data.attachment){
                                    attachment = data.attachment;
                                }

                                if(attachment != ""){
                                    var name = attachment.substring(attachment.lastIndexOf("/")+1);
                                    // onclick="previewFile(\''+name+'\', \''+attachment+'\')"
                                    $('#addHeaderImg').html('<div class="attachments">' +
                                        '<div><img src="../../../admin/assets/images/attachmentsIcon/pdf.png"><span class="file-a">'+name+'</span></div></div>');
                                    $('#attachment').val(attachment);

                                    $(".attachments").click(function () {
                                        var json = {};
                                        json.attachment = attachment;
                                        showViewAttachmentModel(json);
                                    })
                                }

                                // 获取合同保管员
                                admin.req('user/admin/user/list', {limit: 99999}, function(res) {
                                    if (200 == res.code) {
                                        $("form select[name='keeper']").append(new Option("请选择合同保管员", ""));//往下拉菜单里添加元素
                                        $.each(res.data, function(index, item) {
                                            $("form select[name='keeper']").append(new Option(item.nickname+"("+item.username+")", item.id));//往下拉菜单里添加元素
                                        })
                                        form.render(); //菜单渲染 把内容加载进去
                                        if(data && data.keeper){
                                            form.val('contractChangeRecordForm', data);
                                        }
                                    } else {
                                        layer.msg('获取合同保管员失败!', {icon : 2, time : 1000});
                                    }
                                }, 'GET');

                                form.on('switch(isFinal)',function(obj){
                                    if(obj.elem.checked){
                                        $("#content").show();
                                        $("#deliveryTime").attr("lay-verify", "required").attr("required");
                                        $("input[name='address']").attr("lay-verify", "required").attr("required", true);
                                        $("select[name='keeper']").attr("lay-verify", "required").attr("required", true).attr("lay-search", true);
                                        form.render();
                                    }else{
                                        $("#content").hide();
                                        $("#deliveryTime").removeAttr("lay-verify");
                                        $("input[name='address']").removeAttr("lay-verify");
                                        $("select[name='keeper']").removeAttr("lay-verify");
                                    }
                                })

                                if(data){
                                    form.val('contractChangeRecordForm', data);
                                }else{
                                    form.val('contractChangeRecordForm', supplierContract);
                                }
                                // 表单提交事件
                                form.on('submit(contractChangeRecordFormSubmit)', function (d) {
                                    layer.load(2);
                                    var isFinal=$("form input[name='isFinal']").prop("checked");
                                    if(!isFinal){
                                        d.field.isFinal=false;
                                    }else{
                                        d.field.isFinal=true;
                                    }
                                    if(d.field.signingTime){
                                        d.field.signingTime = d.field.signingTime + " 00:00:00";
                                    }
                                    if(d.field.deliveryTime){
                                        d.field.deliveryTime = d.field.deliveryTime + " 00:00:00";
                                    }
                                    d.field.contractId = supplierContract.id;
                                    admin.req(data ? 'enterprise/sell/admin/customerContract/updateContractChangeRecord' : 'enterprise/sell/admin/customerContract/addContractChangeRecord', d.field, function (res) {
                                        layer.closeAll('loading');
                                        if (res.code == 200) {
                                            layer.msg(res.msg, {icon: 1});
                                            isShowAddBtn(supplierContract);
                                            table.reload('contractChangeRecordTable');
                                            layer.close(contractChangeRecord);
                                        } else {
                                            layer.msg(res.msg, {icon: 2});
                                        }
                                    }, data ? 'PUT' : 'POST');
                                    return false;
                                });
                            }
                        });
                    }

                    // 显示审核弹窗
                    function showAuditModel(data) {
                        var contractAudit = admin.open({
                            type: 1,
                            area: ['80%', '80%'],
                            offset: '65px',
                            title: '合同审核',
                            content: $('#contractAuditForm').html(),
                            success: function () {
                                // 查询我方签约人
                                admin.req('user/admin/user/list', {limit: 99999}, function(res) {
                                    if (200 == res.code) {
                                        $.each(res.data, function(index, item) {
                                            if(item.id == data.contractor){
                                                $("#contractorName").text("我方签约人："+item.nickname+"("+item.username+")");
                                            }
                                        })
                                    } else {
                                        layer.msg('获取我方签约人失败!', {icon : 2, time : 1000});
                                    }
                                }, 'GET');

                                // 查询合同保管员
                                admin.req('user/admin/user/list', {limit: 99999}, function(res) {
                                    if (200 == res.code) {
                                        $.each(res.data, function(index, item) {
                                            if(item.id == data.keeper){
                                                $("#keeperName").text("合同保管员："+item.nickname+"("+item.username+")");
                                            }
                                        })
                                    } else {
                                        layer.msg('获取合同保管员失败!', {icon : 2, time : 1000});
                                    }
                                }, 'GET');

                                // 查询信息审批人
                                admin.req('user/admin/user/list', {limit: 99999}, function(res) {
                                    if (200 == res.code) {
                                        $.each(res.data, function(index, item) {
                                            if(item.id == data.approver){
                                                $("#approverName").text("信息审批人："+item.nickname+"("+item.username+")");
                                            }
                                        })
                                    } else {
                                        layer.msg('获取信息审批人失败!', {icon : 2, time : 1000});
                                    }
                                }, 'GET');


                                $("#attachmentName").text("合同附件："+data.attachment.substring(data.attachment.lastIndexOf("/")+1));

                                laytpl(contractInfoHtml.innerHTML).render(data, function (html) {
                                    $("#contractInfo").html(html);
                                });

                                if(data.attachment){
                                    PDFObject.embed(data.attachment, "#example1");
                                }

                                form.val('contractAuditForm', data);

                                // 表单提交事件
                                form.on('submit(contractAuditFormSubmit)', function (d) {
                                    layer.load(2);
                                    d.field.status = $(this).data("status");
                                    admin.req('enterprise/sell/admin/customerContract/auditContractChangeRecord', d.field, function (res) {
                                        layer.closeAll('loading');
                                        if (res.code == 200) {
                                            layer.msg(res.msg, {icon: 1});
                                            isShowAddBtn(supplierContract);
                                            table.reload('contractChangeRecordTable');
                                            layer.close(contractAudit);
                                        } else {
                                            layer.msg(res.msg, {icon: 2});
                                        }
                                    }, 'POST');
                                    return false;
                                });

                            }
                        })
                    }

                    // 终版
                    function doFinal(data) {
                        var contractFinal = admin.open({
                            type: 1,
                            area: ['800px'],
                            offset: '65px',
                            title: '合同终版确认',
                            content: $('#contractFinalForm').html(),
                            success: function () {
                                // 交货时间
                                laydate.render({
                                    elem: '#deliveryTime',
                                    type: 'date'
                                });

                                // 获取合同保管员
                                admin.req('user/admin/user/list', {limit: 99999}, function(res) {
                                    if (200 == res.code) {
                                        $("form select[name='keeper']").append(new Option("请选择合同保管员", ""));//往下拉菜单里添加元素
                                        $.each(res.data, function(index, item) {
                                            $("form select[name='keeper']").append(new Option(item.nickname+"("+item.username+")", item.id));//往下拉菜单里添加元素
                                        })
                                        form.render(); //菜单渲染 把内容加载进去
                                    } else {
                                        layer.msg('获取合同保管员失败!', {icon : 2, time : 1000});
                                    }
                                }, 'GET');

                                form.val('contractFinalForm', data);

                                // 表单提交事件
                                form.on('submit(contractFinalFormSubmit)', function (d) {
                                    layer.load(2);
                                    if(d.field.deliveryTime){
                                        d.field.deliveryTime = d.field.deliveryTime + " 00:00:00";
                                    }
                                    admin.req('enterprise/sell/admin/customerContract/setContractFinal', d.field, function (res) {
                                        layer.closeAll('loading');
                                        if (res.code == 200) {
                                            layer.msg(res.msg, {icon: 1});
                                            isShowAddBtn(supplierContract);
                                            table.reload('contractChangeRecordTable');
                                            table.reload('contractTable');
                                            layer.close(contractFinal);
                                        } else {
                                            layer.msg(res.msg, {icon: 2});
                                        }
                                    }, 'POST');
                                    return false;
                                });

                            }
                        })

                    }

                }
            })
        }

        // 关联物料
        function showRelatedProductModel(data) {
            var contractData = data;
            admin.open({
                type: 1,
                area: ['80%', '85%'],
                title: '合同关联物料',
                content: $('#contractRelatedProduct').html(),
                success: function () {
                    console.log(contractData);

                    // 渲染表格
                    table.render({
                        elem: '#contractRelatedProductContractTable',
                        // url: config.base + 'enterprise/sell/admin/customerContract/list',
                        // where: {id: data.id},
                        data: [contractData],
                        page: false,
                        cellMinWidth: 100,
                        cols: [[
                            {type: 'numbers'}
                            ,{field: 'code', align:'center', title: '合同编号', width: 150}
                            ,{field: 'typeDesc', align:'center', title: '合同主体类型', width: 140}
                            ,{field: 'companyName', align:'center', title: '客户名称', width: 120}
                            ,{field: 'contractCategoryName', align:'center', title: '合同分类', width: 120}
                            ,{field: 'createTime', align:'center', title: '创建时间', width: 160}
                            ,{field: 'contactName', align:'center', title: '客户签约人', width: 120}
                            ,{field: 'amount', align:'center', title: '签约金额', width: 110}
                            ,{field: 'attachment', align:'center', title: '合同附件', width: 110, toolbar: '#viewAttachmentBar'}
                            ,{field: 'statusDesc', align:'center', title: '合同状态', width: 110}
                            ,{align:'center', title: '操作', width: 120, toolbar: '#customerPhoneBar'}
                        ]],
                        done: function (res, curr, count) {

                        }
                    });

                    // 渲染表格
                    table.render({
                        elem: '#contractRelatedProductTable',
                        // url: config.base + 'enterprise/sell/admin/customerContract/contractRelatedProductList',
                        // where: {contractId: data.id},
                        data: [],
                        page: false,
                        cellMinWidth: 100,
                        cols: [[
                            {type: 'numbers'}
                            ,{field: 'code', align:'center', title: '客户物料编码(SKU料号)', width: 190}
                            ,{field: 'typeDesc', align:'center', title: '客户物料名称', width: 140}
                            ,{field: 'companyName', align:'center', title: '客户规格名称', width: 120}
                            ,{field: 'contractCategoryName', align:'center', title: '内部物料料号（SKU编码）', width: 200}
                            ,{field: 'createTime', align:'center', title: '内部物料类型', width: 150}
                            ,{field: 'contactName', align:'center', title: '内部规格码', width: 120}
                            ,{field: 'attachment', align:'center', title: '合同附件', width: 110, toolbar: '#viewAttachmentBar'}
                            ,{field: 'amount', align:'center', title: '描述', width: 110}
                            ,{field: 'statusDesc', align:'center', title: '物料状态', width: 110}
                            ,{align: 'center', toolbar: '#contractChangeRecordTableBar', title: '操作', width: 200}
                        ]],
                        done: function (res, curr, count) {

                        }
                    });

                    // 工具条点击事件
                    table.on('tool(contractRelatedProductContractTable)', function (obj) {
                        var data = obj.data;
                        if (obj.event === 'viewAttachment') { // 查看附件
                            showViewAttachmentModel(data);
                        } else if (obj.event === 'viewCustomerPhone') { // 查看客户手机号
                            viewCustomerPhone(data);
                        }
                    });

                    // 添加合同物料信息
                    $("#addContractProductInfo").click(function () {
                        showEditModel();
                    })

                    // 查看客户手机号
                    function viewCustomerPhone(data) {
                        admin.open({
                            title: '客户手机号',
                            content: data.contactPhone
                        }, {
                            offset: '65px',
                            skin: 'layui-layer-admin'
                        });
                    }

                    // 显示编辑弹窗
                    function showEditModel(data) {
                        var contractRelatedProduct = admin.open({
                            type: 1,
                            area: ['70%', '70%'],
                            offset: '65px',
                            title: data ? '修改合同物料信息' : '添加合同物料信息',
                            content: $('#contractRelatedProductForm').html(),
                            success: function () {
                                //自定义验证规则
                                form.verify({
                                    decimal: [/^[0-9]*(\.[0-9]{1,2})?$/, '格式错误'],
                                    attachment: function (value) {
                                        if(value == ""){
                                            return "请上传附件";
                                        }
                                    }
                                })

                                // 查询客户信息
                                admin.req('enterprise/sell/admin/customerContract/getCustomerInfo', {subjectId: subjectId, contactsId: contactsId}, function(res) {
                                    if (200 == res.code) {
                                        console.log(res.data);
                                        // 渲染表格
                                        table.render({
                                            elem: '#contractRelatedProductTable',
                                            // url: config.base + 'enterprise/sell/admin/customerContract/contractRelatedProductList',
                                            // where: {contractId: data.id},
                                            data: [res.data],
                                            page: false,
                                            cellMinWidth: 100,
                                            cols: [[
                                                {type: 'numbers'}
                                                ,{field: 'code', title: '客户物料编码', width: 130}
                                                ,{field: 'typeDesc', title: '客户物料名称', width: 140}
                                                ,{field: 'companyName', title: '客户规格名称', width: 120}
                                                ,{field: 'contractCategoryName', title: '内部物料料号', width: 120}
                                                ,{field: 'createTime', title: '内部物料类型', width: 170}
                                                ,{field: 'contactName', title: '内部规格码', width: 120}
                                                ,{field: 'attachment', title: '合同附件', width: 110, toolbar: '#viewAttachmentBar'}
                                                ,{field: 'amount', title: '描述', width: 110}
                                                ,{field: 'statusDesc', title: '物料状态', width: 110}
                                                ,{align: 'center', toolbar: '#contractChangeRecordTableBar', title: '操作', width: 200}
                                            ]],
                                            done: function (res, curr, count) {

                                            }
                                        });
                                    } else {
                                        layer.msg('获取客户信息失败!', {icon : 2, time : 1000});
                                    }
                                }, 'GET');

                            }
                        });
                    }

                }
            })
        }

        // 查看附件
        function showViewAttachmentModel(data) {
            admin.open({
                type: 1,
                area: ['60%', '80%'],
                title: '查看附件',
                content: $('#viewAttachmentHtml').html(),
                success: function () {
                    
                    if(data.attachment){
                        PDFObject.embed(data.attachment, "#example1");
                    }else{
                        layer.msg('合同未签约或附件不存在', {icon: 2});
                    }
                }
            })
        }

        // 是否显示添加合同变更记录按钮
        function isShowAddBtn(data){
            admin.req('enterprise/sell/admin/customerContract/isShowAddBtn', {id: data.id}, function(res) {
                if (200 == res.code) {
                    if(res.data){
                        $("#opBtn").show();
                    }else{
                        $("#opBtn").hide();
                    }
                }
            }, 'GET');
        }

        // 导出excel
        $('#contractBtnExport').click(function () {
            var checkRows = table.checkStatus('contractTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要导出的数据', {icon: 2});
            } else {
                table.exportFile(insTb.config.id, checkRows.data, 'xls');
            }
        });

    });
</script>